import { defineStore } from "pinia";
import { getRoot, getInfo, getHistory,getSlideList ,addSliderFlow,delSliderFlow} from "@/api/home/index";
import { saveLocal, getLocal } from "@/utils/common";
import { ElMessage} from "element-plus"

export const useProcessFlow = defineStore("processFlow", {
  state: () => {
    return { count: 0 };
  },
  // 也可以定义为
  // state: () => ({ count: 0 })
  actions: {
    increment() {
      this.count++;
    },
  },
});
//
export const useRootData = defineStore("rootData", {
  state: () => ({
    source: getLocal("root-data-source") as any,
    processNodes: getLocal("root-data-processNodes") as any,
    // groupsNodes: getLocal("root-data-groupsNodes") as any,
    updateTime: getLocal("root-data-updateTime") || 0,
    slideList: getLocal("root-data-slideList") || ([] as any[]),
  }),
  actions: {
    async init(noCache = false) {
      const t = new Date().getTime() - this.updateTime;
      if(t < 1000) return ;
      if(t > 60000 || noCache != false){
        try {
          const res = await getRoot();
          //
          const data = res.data;
          this.source = data;
          // const tgs = data.processGroupFlow.flow.processGroups;
          // this.groupsNodes = groupArray(tgs, "component.catalog");
          this.processNodes = data.processGroupFlow.flow.processors;
          this.updateTime = new Date().getTime(); 
          //
          saveLocal("root-data-source", data);
          saveLocal("root-data-processNodes", this.processNodes);
          // saveLocal("root-data-groupsNodes", this.groupsNodes);
          saveLocal("root-data-updateTime", this.updateTime);
        } catch (error) {
          console.log("=====init root data error=====", error);
        }
      }
      

      this.initSlideList();
    },
    async initSlideList() {
      try {
        const res = await getSlideList();
        const gns:Record<string,any[]> = res.data || {};
        const list = Object.keys(gns).map((k,i) => ({
          name:k,
          id:i + Math.random(),
          children:gns[k].map((c) => ({id:c.id,name:c.status.name,data:c}))
        }))
        this.slideList = list;
        //
        saveLocal("root-data-slideList", list);
      } catch (error) {
        console.warn('initSlideList ========> ',error)
      }
    },
    async addSlideFlow(data:{subprocess:string,catalog:string}){
      if(!data){return ;}
      try {
        const res = await addSliderFlow(data)
        const item = res.data;
        ElMessage({message:"新增流程成功",type: 'success'})
        //
        await this.initSlideList();
        return item;
      } catch (error:any) {
        console.warn('addSlideFlow ==========> ',error)
        const msg = error?.response?.data;
        ElMessage({message:msg || "新增流程失败",type: 'error'})
      }
      return false;
    },
    async delSlideFlow(id:string){
      if(!id){return ;}
      try {
        const res = await delSliderFlow(id)
        const item = res.data;
        ElMessage({message:"删除流程成功",type: 'success'})
        //
        await this.initSlideList();
        return item;
      } catch (error:any) {
        console.warn('delSlideFlow ==========> ',error);
        const msg = error?.response?.data;
        ElMessage({message:msg || "删除流程失败",type: 'error'})
      }
      return false;
    },
    getItemGroupList(item:any){
      const id = item.id;
      const list = this.slideList;
      let res = []
      if(id){
        for(const cs of list){
          const t = cs.children?.filter((d:any) => d.id == id)
          if(t.length == 1){
            res = cs.children.map((d:any) => d.data)
            break;
          }
        }
      }
      return res;
    }
  },
});

// 当前数据
export const useCurrentData = defineStore("currentData", {
  state: () => ({
    bread: ["测试", "test1", { name: "test2" }] as any[],
    activeItem: getLocal("current-data-activeItem") as any,
    activeItemName:'' as string,
    activeGroupName: getLocal("current-data-activeGroupName") || ("" as string),
    activeGroups: getLocal("current-data-activeGroups") || ([] as any[]),
    info: getLocal("current-data-info") as any,
    processList: getLocal("current-data-activeGroups") || ([] as any[]),
    nodes:[] as any[],
    nodesList: getLocal("current-data-nodesList") || ([] as any[]),
    openCacheIds: [] as string[],
    chartData: [] as any[],
    refreshTimeHandle: undefined as any,
    slideCollapse:false, // 菜单的折叠状态
    nodesChartData:{} as Record<string,any>,
    isFullScreen:false,
    isDetail:false,
  }),
  actions: {
    clearActiveItem(){
      this.activeItem = undefined;
      this.activeItemName = "";
      this.activeGroupName = "";
      this.activeGroups = [];
      this.processList = [];
      saveLocal("current-data-activeItem", this.activeItem);
      saveLocal("current-data-activeGroupName", this.activeGroupName);
      saveLocal("current-data-activeGroups", this.activeGroups);
    },
    resetActiveItem(item: any, list: any[]) {
      if (item.id == this.activeItem?.id) {
        return;
      }
      this.activeItem = item;
      this.activeItemName = item.status.name;
      this.activeGroupName = item.component.catalog;
      this.activeGroups = list;
      this.processList = list;
      //
      saveLocal("current-data-activeItem", item);
      saveLocal("current-data-activeGroupName", this.activeGroupName);
      saveLocal("current-data-activeGroups", list);
      //
      this.initProcessList();
      //
      this.refreshActiveNode();
      //
      this.initChartData();
    },
    async initProcessList() {
      const item = this.activeItem;
      const id = item.id;
      const t = new Date().getTime();
      const { time = 0, value } =
        getLocal("current-data-processList-" + id, true) || {};
      //
      let data = value;
      if (t - time > 60000) {
        try {
          const res = await getInfo(item);
          data = res.data;
          saveLocal("current-data-processList-" + id, data);
        } catch (error) {
          console.warn("====initProcessList====", item);
        }
      }
      //
      try {
        const flow = data.processGroupFlow.flow;
        const l = [...flow.processGroups, ...flow.processors]
        const list = l.map(
          (item) => ({ label: item.status.name, value: item.id })
        );
        //
        this.info = data;
        this.nodes = l;
        this.nodesList = list;
        // this.nodesListIds = list.map((d:any) => d.id)
        //
        saveLocal("current-data-info", this.info);
        saveLocal("current-data-nodesList", this.nodesList);
      } catch (error) {
        console.warn("=====initProcessList======", error);
      }
    },
    async refreshActiveNode() {
      // 刷新
      if (this.refreshTimeHandle) {
        clearInterval(this.refreshTimeHandle);
      }
      this.refreshTimeHandle = setInterval(async () => {
        const item = this.activeItem || {};
        const id = item.id;
        if(!id) {return ;}
        try {
          const res = await getInfo(item);
          const data = res.data;
          const t = data.processGroupFlow;
          item.status.statsLastRefreshed = t.lastRefreshed;
        } catch (error) {
          console.warn('=====refreshActiveNode====')
        }
      },10000);
    },
    async initChartData() {
      const item = this.activeItem;
      this.getChartData(item)
    },
    resetSlideCollapse(bool:boolean){
      this.slideCollapse = bool;
    },
    async getChartData(item:any){
      const id = item.id;
      try {
        const res = await getHistory(item);
        const d = res.data;
        const t = d?.statusHistory || {};
        const a = t?.aggregateSnapshots || [];
        const data = a.length > 10 ? a.slice(-10) : [...a];
        this.nodesChartData[id] = data;
      } catch (error) {
        console.warn('getChartData =======> ',error)
      }
    },
    updateChartData(ids:string|string[] = []){
      console.log('====refreshChart======',ids)
      const ks:string[] = ([] as string[]).concat(ids);
      const items = this.nodes.filter((d:any) => ks.includes(d.id));
      if(items.length > 0){
        for(const item of items){
          this.getChartData(item)
        }
      }
    },
    refreshChartData(){
      const cks = Object.keys(this.nodesChartData)
      const items = [this.activeItem,...(this.nodes.filter((d:any) => cks.includes(d.id)))]
      for(const item of items){
        this.getChartData(item)
      }
    },
    resetIsFullScreen(bool?:boolean){
      const v = bool ?? !this.isFullScreen;
      this.isFullScreen = v;
    },
    resetIsDetail(bool?:boolean){
      const v = bool ?? !this.isDetail;
      this.isDetail = v;
      if(v){
        this.isFullScreen = false;
      }
    },
  },
});

// API
export const useNifiApi = defineStore("nifiApi",{
  actions:{

  }
})